<?php
/**
 * Copyright (c) 2010, Slawomir Mazur <mazursllawek@gmail.com>
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions 
 * are met:
 * 
 * o Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * o Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * o Neither the name of the Softisland nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * Enter description here...
 *
 * @package     System
 * @copyright   Slawomir Mazur (c) 2010 (http://www.zend.com/zce.php?c=ZEND011643)
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @author      Slawomir Mazur <mazursllawek@gmail.com>
 */

class System_Model_Table extends Zend_Db_Table_Abstract
{
	protected $_name = '';
	
	protected $_primary = '';

	const TABLE_EXISTS = 'SHOW TABLES';
	
	const COLUMN_EXISTS = 'SHOW COLUMNS FROM `history`';
	
	const CREATE_TABLE =
	'CREATE TABLE `%s` (
		`%s_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
		`value` VARCHAR( 500 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL
	) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci';
	
	const CREATE_COLUMN = 'ALTER TABLE `history` ADD `%s` %s%s %s';
	
	const EDIT_TABLE = 'RENAME TABLE `%s` TO `%s`';
	
	const EDIT_COLUMN = 'ALTER TABLE `history` CHANGE `%s` `%s` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL';
	
	const DROP_TABLE = 'DROP TABLE `%s`';
	
	const DROP_COLUMN = 'ALTER TABLE `history` DROP `%s`';
	
	protected $_collection = null;
	
	public function getCollection()
	{
		$select = $this->select()->order('name');
		
		return $this->fetchAll($select);
	}
	
	/**
	 * Check whether table with $name exists
	 * 
	 * @param string $tableName
	 * @return boolean
	 */
	public function tableExists($tableName)
	{
		$db = $this->getAdapter();

		$tables = $db->query(self::TABLE_EXISTS)->fetchAll();

		foreach ($tables as $tableSpec) {
			if (is_array($tableSpec)) {
				if (current($tableSpec) == $tableName) {
					throw new Exception('Table `' . $tableName . '` already exists in database');
				}
			} else if (is_string($tableSpec)) {
				if ($tableSpec == $tableName) {
					throw new Exception('Table `' . $tableName . '` already exists in database');
				}
			}
		}

		return false;
	}
	
	/**
	 * Check whether column with $name exists
	 * 
	 * @param string $columnName
	 * @return boolean
	 */
	public function columnExists($columnName)
	{
		$db = $this->getAdapter();

		$columns = $db->query(self::COLUMN_EXISTS)->fetchAll();
		
		foreach ($columns as $columnSpec) {
			if (is_array($columnSpec)) {
				if ($columnSpec['Field'] == $columnName) {
					throw new Exception('Column `' . $columnName . '` already exists!');
				}
			} else if (is_string($columnSpec)) {
				if ($columnSpec == $columnName) {
					throw new Exception('Column `' . $columnName . '` already exists!');
				}
			}
		}

		return false;
	}	
	
	/**
	 * Try to create table
	 * 
	 * @param string $tableName
	 */
	public function createTable($tableName)
	{
		$db = $this->getAdapter();
		$db->query(sprintf(self::CREATE_TABLE, $tableName, $tableName));
	}
	
	/**
	 * Try to create append column
	 * 
	 * @param $columnName
	 * @param $columnType
	 * @param $columnTypeSize
	 */
	public function createColumn($columnName, $columnType, $columnTypeSize)
	{
		$db = $this->getAdapter();		
		switch ($columnTypeSize) {
			case 'yes,no' :
				$db->query(sprintf(self::CREATE_COLUMN, $columnName, 'ENUM', '(\'yes\', \'no\')', 'NOT NULL DEFAULT \'no\''));
				break;
			case '-' :
				$db->query(sprintf(self::CREATE_COLUMN, $columnName, $columnType, '', ''));
				break;
			case (false !== strpos($columnType, 'int')) :
				$db->query(sprintf(self::CREATE_COLUMN, $columnName, $columnType, '(' . $columnTypeSize . ') UNSIGNED', 'NOT NULL DEFAULT \'0\''));
				break;
			default:
				$db->query(sprintf(self::CREATE_COLUMN, $columnName, $columnType, '(' . $columnTypeSize . ')', 'NULL'));
				break;
		}
	}
	
	/**
	 * Change table name
	 * 
	 * @param string $oldTableName
	 * @param string $newTableName
	 */
	public function changeTableName($oldTableName, $newTableName)
	{
		$db = $this->getAdapter();
		$db->query(sprintf(self::EDIT_TABLE, $oldTableName, $newTableName));
	}
	
	/**
	 * Change column name
	 * 
	 * @param string $oldColumnName
	 * @param string $newColumnName
	 */
	public function changeColumnName($oldColumnName, $newColumnName)
	{
		$db = $this->getAdapter();
		$db->query(sprintf(self::EDIT_COLUMN, $oldColumnName, $newColumnName));
	}
	
	/**
	 * Drop table
	 * 
	 * @param string $tableName
	 */
	public function dropTable($tableName)
	{
		$db = $this->getAdapter();
		$db->query(sprintf(self::DROP_TABLE, $tableName));
	}
	
	/**
	 * Drop column
	 * 
	 * @param string $tableName
	 */
	public function dropColumn($columnName)
	{
		$db = $this->getAdapter();		
		$db->query(sprintf(self::DROP_COLUMN, $columnName));
	}
}